package com.rpp.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.rpp.io.Resource;
import com.rpp.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XmlSqlMapCofigBuilder {

    private Configuration configuration;

    public XmlSqlMapCofigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parse(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document read = new SAXReader().read(inputStream);
        Element rootElement = read.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            properties.put(element.attributeValue("name"), element.attributeValue("value"));
        }
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(dataSource);

        List<Element> mapper = rootElement.selectNodes("//mapper");
        for (Element element : mapper) {
            String resource = element.attributeValue("resource");
            InputStream inputStream1 = Resource.loadResource(resource);
            XmlMapperBuider xmlMapperBuider = new XmlMapperBuider(configuration);
            xmlMapperBuider.parse(inputStream1);
        }
        return configuration;
    }
}
